const express = require('express');
const router = express.Router();
const { body, validationResult } = require('express-validator');
const boom = require('boom');

const Result = require('../models/result');
const { login, findUser, register } = require('../services/user');
const { sign, md5 } = require('../utils');
const { PWD_SALT } = require('../utils/constant');

/*
 * 登录接口
 */
router.post('/login', [
	body('username').isString().withMessage('username类型不正确'),
	body('password').isString().withMessage('password类型不正确')
], (req, res, next) => {
	const err = validationResult(req);
	if (!err.isEmpty()) {
		const [{ msg }] = err.errors;
		next(boom.badRequest(msg));
	} else {
		const username = req.body.username;
		const password = req.body.password;
		login(username, password).then(user => {
			if (!user || user.length === 0) {
				new Result('登录失败').fail(res);
			} else {
				const token = sign({
					userid:user[0].id, 
					username:username,
				});
				new Result({ token }, '登录成功').success(res);
			}
		});
	}
});

/*
 * 获取当前用户接口
 */
router.get('/info', function (req, res, next) {
	const decoded = req.user;
	if (decoded && decoded.username) {
		findUser(decoded.username).then(user => {
			if (user) {
				user.roles = [user.role];
				new Result(user, '获取用户信息成功').success(res);
			} else {
				new Result('获取用户信息失败').fail(res);
			}
		}).catch(err => {
			new Result(err.sqlMessage).fail(res);
		});
	} else {
		new Result('用户信息解析失败').fail(res);
	}
});

/*
 * 注册接口
 */
router.post('/register', [
	body('username').isString().withMessage('username类型不正确'),
	body('password').isString().withMessage('password类型不正确')
], (req, res, next) => {
	const err = validationResult(req);
	if (!err.isEmpty()) {
		const [{ msg }] = err.errors;
		next(boom.badRequest(msg));
	} else {
		let data = req.body;
		data.password = md5(`${data.password}${PWD_SALT}`);
		register(data).then(stats => {
			new Result("注册用户成功").success(res);
		}).catch(err => {
			new Result(err.sqlMessage).fail(res);
		});
	}
});

module.exports = router;
